package com.ars.db;

import java.sql.*;

public class DBTools {
    private static final String HOST_NAME = "127.0.0.1";

    private Connection ct = null;
    private Statement sm = null;
    private ResultSet rs = null;

    public DBTools() {
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取链接
            ct = DriverManager.getConnection("jdbc:mysql://" + HOST_NAME + ":3306/airline_reservation_system", "root", "123456");
            sm = ct.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭数据库
     */
    public void close() {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (sm != null) {
                sm.close();
                sm = null;
            }
            if (ct != null) {
                ct.close();
                ct = null;
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    /**
     * 更新数据库
     *
     * @param sql
     * @return
     */
    public int update(String sql) {
        try {
            return sm.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 查询数据库
     *
     * @param sql
     * @return ResultSet
     */
    public ResultSet query(String sql) {
        try {
            return sm.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
